# 如何使用Python继承机制（子类化内置类型）
class newDictError(ValueError):
    '''如果向 newDict 添加重复值，则引发此异常'''
    pass

class newDict(dict):
    '''不接受重复值的字典'''
    def __setitem__(self, key, value):
        if value in self.values():
            if ((key in self and self[key] != value) or (key not in self)):
                raise newDictError("这个值已经存在，并对应不同的键")
        super().__setitem__(key, value)

demoDict = newDict()
demoDict["key"] = "value"
demoDict["other_key"] = "value2"
print(demoDict)
#demoDict["other_key"] = "value" # __main__.newDictError: 这个值已经存在，并对应不同的键
print(demoDict)
print()

class myList(list):
    def __init__(self, name):
        self.name = name
    
    def dir(self, nesting = 0):
        offset = " " * nesting
        print("%s%s/" % (offset, self.name))
    
        for element in self:
            if hasattr(element, "dir"):
                element.dir(nesting + 1)
            else:
                print("%s %s" % (offset, element))

demoList = myList("C语言中文网")
demoList.append("http://c.biancheng.net")
print(demoList.dir())
